package common;

import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 平滑加权轮询算法
 *
 * @author K
 * @date 2024-04-09 20:23
 */
public class RoundRobin {

    private List<Server> list = new ArrayList<>();
    private Integer totalWeight = 0;

    RoundRobin() {

    }


    public static void main(String[] args) {
        RoundRobin roundRobin = new RoundRobin();
        roundRobin.addServer("A", 3);
        roundRobin.addServer("B", 2);
        roundRobin.addServer("C", 1);

        for (int i = 0; i < 10; i++) {
            Server server = roundRobin.chooseServer();
            System.out.printf("第%d次调用，选择实例：\t%s \n", i + 1, server);
        }
    }

    public Server chooseServer() {
        list = list.stream().peek(x -> x.weight += x.baseWeight)
                .sorted().collect(Collectors.toList());
        Server win = list.get(0);
        win.weight -= totalWeight;

        return win;
    }

    public void addServer(String name, Integer weight) {
        Server server = new Server();
        server.setName(name);
        server.setWeight(0);
        server.setBaseWeight(weight);
        list.add(server);
        totalWeight += weight;
    }

    @Data
    static class Server implements Comparable<Server> {
        public String name;
        public Integer baseWeight;
        public Integer weight;

        @Override
        public int compareTo(Server o) {
            return o.weight.compareTo(this.weight);
        }

        public String toString() {
            return name;
        }
    }

}
